package com.billionsfinance.crs.hessian.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @ ClassName: SpringContextUtils.java
 * @ Author: WeiHui-Z
 * @ Date: 2017/1/4 17:08
 * @ Version: v1.0.0
 */
public class SpringContextUtils implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext context;

	/**
	 * 销毁
	 *
	 * @throws Exception 异常信息
	 */
	@Override
	public void destroy() throws Exception {
		SpringContextUtils.context = null;
	}

	/**
	 * 赋值上下文
	 *
	 * @param applicationContext 上下文
	 * @throws BeansException 异常信息
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtils.context = applicationContext;
	}

	/**
	 * 根据BeanName获取Bean
	 *
	 * @param name BeanName
	 * @return Object 获取的Bean对象
	 */
	public static Object getBean(String name) {
		return context.getBean(name);
	}

	/**
	 * 根据Class获取Bean对象
	 *
	 * @param clazz BeanClass
	 * @param <T>   T
	 * @return T 获取Bean对象
	 */
	public static <T> T getBean(Class<T> clazz) {
		return context.getBean(clazz);
	}

	/**
	 * 获取注入的Bean
	 *
	 * @param clazz
	 * @param <T>   t
	 * @return <T> T
	 */
	public static <T> T getAutowireBean(Class<T> clazz) {
		return context.getAutowireCapableBeanFactory().getBean(clazz);
	}

	/**
	 * 获取自动注入的Bean
	 *
	 * @param name BeanName
	 * @return Object 注入的对象
	 */
	public static Object getAutowireBean(String name) {
		return context.getAutowireCapableBeanFactory().getBean(name);
	}
}
